#coding=utf-8

from google.appengine.api import runtime
from google.appengine.ext import db, webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from model.batch_log import BatchLog
from model.stream import Stream
from model.subscription import Subscription
from model.user import User
import logging

class SubscribeHandler(webapp.RequestHandler):

    def _write_error(self, error_message):
        self.error(400)
        self.response.out.write(error_message)

    def get(self):
        logging.info('SubscribeHandler get')

    def post(self):
        '''
        1386 fff
        1387 ggg subscriber
        '''
        logging.info('generateSubscription begin')
        user = User.get_by_key_name(key_names=str(1386))
        subscriber = User.get_by_key_name(key_names=str(1387))
        if user is None or subscriber is None:
            logging.info('no user or no subscriber, exit!')
            return
        stream = Stream.get_or_insert(key_name=str(1386),
                                      owner=str(user.key()),
                                      owner_uid=user.user_id,
                                      title='test_stream')
        logging.info('stream owner_uid=%s, subscriber id=%s' %
                     (stream.owner_uid, subscriber.user_id))
        try:
            i = int(self.request.get('batch'))
        except ValueError:
            self._write_error('"batch" is not an integer.')
            logging.error('"batch" is not an integer.')
            return
        subscriptions = []
        stats = 0
        memoryUsage = runtime.memory_usage().current()
        cpuUsage = runtime.cpu_usage().rate10m()
        batchLog = BatchLog.get_by_key_name(key_names=str(i))
        if batchLog:
            logging.info('batch %d to be continue' % i)
            return
        limit=1000
        for j in range(0, limit, 1):
            state = '%d_%d' % (i, j)
            subscription = Subscription(streamkey=str(stream.key()), subscriber=str(subscriber.key()),
                                        subscriber_uid=subscriber.user_id, target='test', state=state)
            subscriptions.append(subscription)
        db.put(subscriptions)

        if len(subscriptions) == limit:
            stats = 1
        batchLog = BatchLog(key_name=str(i), batch=i,
                            batch_size=len(subscriptions),
                            user_id=stream.owner_uid,
                            subscriber_id=subscriber.user_id, stats=stats)
        db.put_async(batchLog)
        logging.info('batch=%d, memory usage=%d, cpu usage=%d stats=%d, user id=%d, subscriber id=%d' %
                     (i, memoryUsage, cpuUsage, stats, stream.owner_uid, subscriber.user_id))



class StartHandler(webapp.RequestHandler):
    def get(self):
        logging.info('StartHandler')


_handlers = [(r'/_ah/start', StartHandler),
             (r'/backend/sub_worker/add$', SubscribeHandler)]

application = webapp.WSGIApplication(_handlers)


def main():
    run_wsgi_app(application)

if __name__ == '__main__':
    main()
